# -*- coding: utf-8 -*-
# Copyright 2011-2012 MagiCycles.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import logging

from siteutils import render_to_response
from oauth.utils import OAuthError
from apis.utils import APIRESTDispatcher,returnjson,METHODS,returnjsoncallback

def apisindex(request):
    return render_to_response("apis.html", {})

def methods(request):
    context = {"methods": METHODS.items(),
               }    
    return render_to_response("methods.html", context)

def rest(request):
    dispatcher = APIRESTDispatcher.get_dispatcher(request)

    try:
        result = dispatcher.dispatch(request)
    except OAuthError, e:
        logging.exception(str(e))
        result = {"status": 401,
                  "message": str(e), }
    except Exception, e:
        logging.exception(str(e))
        result = {"status": 500,
                  "message": str(e), }

    try:
        custom_encoder = result.pop("custom_encoder",None)
        if dispatcher.jsoncallback:
            return returnjsoncallback(result, dispatcher.jsoncallback, default=custom_encoder)
        else:
            return returnjson(result, default=custom_encoder)
    except Exception, e:
        logging.exception(str(e))
        return returnjson({"status": 500,
                  "message": str(e), })

def main():
    pass

if __name__ == '__main__':
    main()
